package com.example.bingobox.ui.invoke;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.bingobox.databinding.ItemInvokeBinding;
import com.example.bingobox.model.TodoBox;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class InvokeAdapter extends RecyclerView.Adapter<InvokeAdapter.ViewHolder> {
    private final Context context;
    private final Random random = new Random();
    private final Gson gson = new Gson();
    private List<TodoBox> todoBoxes;
    private Set<String> drawnTaskIds = new HashSet<>();
    private Map<String, Map<String, Object>> taskMap;
    private String currentCityType;

    public InvokeAdapter(Context context, List<TodoBox> todoBoxes, Map<String, Map<String, Object>> taskMap) {
        this.context = context;
        this.todoBoxes = todoBoxes;
        this.taskMap = taskMap;
    }

    public void updateTodoBoxes(List<TodoBox> newTodoBoxes) {
        this.todoBoxes = newTodoBoxes;
        drawnTaskIds.clear();  // 清空已抽取任务列表
        notifyDataSetChanged();
    }

    public void updateTaskMap(Map<String, Map<String, Object>> newTaskMap) {
        this.taskMap = newTaskMap;
    }

    public void updateCityType(String cityType) {
        this.currentCityType = cityType;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemInvokeBinding binding = ItemInvokeBinding.inflate(
                LayoutInflater.from(parent.getContext()), parent, false);
        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        TodoBox todoBox = todoBoxes.get(position);
        
        holder.binding.textTodoboxName.setText(todoBox.getName());
        holder.binding.textTodoboxDescription.setText(todoBox.getDescription());
        
        // 设置抽取按钮点击事件
        holder.binding.btnDraw.setOnClickListener(v -> {
            if (todoBox.getListData() == null || todoBox.getListData().getList() == null || 
                todoBox.getListData().getList().isEmpty()) {
                Toast.makeText(context, "无可用任务", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 获取该任务盒中未被抽取的任务
            List<TodoBox.TaskRef> availableTasks = new ArrayList<>();
            for (TodoBox.TaskRef taskRef : todoBox.getListData().getList()) {
                // 检查任务是否已被抽取
                if (!drawnTaskIds.contains(taskRef.getTaskId())) {
                    // 检查任务是否在任务列表中
                    Map<String, Object> task = taskMap.get(taskRef.getTaskId());
                    if (task != null) {
                        // 检查任务时间是否有效
                        if (task.containsKey("deadline")) {
                            long deadline = ((Number) task.get("deadline")).longValue();
                            if (deadline > 0 && deadline < System.currentTimeMillis()) {
                                continue; // 跳过已过期的任务
                            }
                        }

                        // 检查任务的城市类型匹配
                        boolean isHometown = task.containsKey("isHometown") && 
                                           (Boolean) task.get("isHometown");
                        boolean isResidence = task.containsKey("isResidence") && 
                                            (Boolean) task.get("isResidence");
                        
                        // 根据 isHometown 和 isResidence 确定城市类型
                        String taskCityType;
                        if (isHometown && isResidence) {
                            taskCityType = "大本营";
                        } else if (isHometown) {
                            taskCityType = "老家";
                        } else if (isResidence) {
                            taskCityType = "常住城市";
                        } else {
                            taskCityType = "旅游出差";
                        }
                        
                        // 检查城市类型是否匹配
                        if (currentCityType != null && !currentCityType.equals(taskCityType)) {
                            continue; // 跳过城市类型不匹配的任务
                        }

                        availableTasks.add(taskRef);
                    }
                }
            }
            
            if (availableTasks.isEmpty()) {
                Toast.makeText(context, "当前没有可抽取的任务", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 随机抽取一个任务
            TodoBox.TaskRef selectedTask = availableTasks.get(random.nextInt(availableTasks.size()));
            drawnTaskIds.add(selectedTask.getTaskId());  // 添加到已抽取列表
            
            // 构建任务详细信息
            StringBuilder message = new StringBuilder();
            message.append("任务名称：").append(selectedTask.getName()).append("\n\n");
            
            // 获取完整的任务信息
            Map<String, Object> task = taskMap.get(selectedTask.getTaskId());
            if (task != null) {
                // 添加任务描述
                if (task.containsKey("description") && task.get("description") != null) {
                    String description = task.get("description").toString();
                    if (!description.isEmpty()) {
                        message.append("描述：").append(description).append("\n\n");
                    }
                }
                
                // 添加截止时间
                if (task.containsKey("deadline")) {
                    long deadline = ((Number) task.get("deadline")).longValue();
                    if (deadline > 0) {
                        message.append("截止时间：").append(formatDate(deadline));
                    }
                }
            }

            // 显示抽取到的任务
            new MaterialAlertDialogBuilder(context)
                .setTitle("抽取到的任务")
                .setMessage(message.toString())
                .setPositiveButton("确定", null)
                .setNegativeButton("重新抽取", (dialog, which) -> {
                    // 递归调用显示新任务
                    holder.binding.btnDraw.performClick();
                })
                .show();
        });
    }

    @Override
    public int getItemCount() {
        return todoBoxes.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        final ItemInvokeBinding binding;

        ViewHolder(ItemInvokeBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }

    // 添加日期格式化方法
    private String formatDate(long timestamp) {
        if (timestamp == 0) {
            return "无截止日期";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
        return sdf.format(new Date(timestamp));
    }
}
